<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/1
 * Time: 13:08
 */
namespace Admin\Model;
use IDCU\Model\RelationModel;

class CustomerModel extends RelationModel
{
    protected $_validate = array(
        array('name','require','姓名必填'),
        array('sex','require','性别必填'),
        array('tel','/^1[34578]\d{9}$/','请填写正确的手机号',0,'regex',3),
        array('tel','','该手机号已注册',0,'unique',1),
        array('phone','','该电话号码已注册',0,'unique',1),
        array('id_no','','该身份证号码已注册',0,'unique',3),
    );

    protected $_auto = array(
        array('customer_no','getCustomerId',1,'callback'),
        array('create_time','time',1,'function'),
        array('modify_time','time',3,'function'),
        array('creator_id','getUserId',1,'function'),
        array('modifier_id','getUserId',3,'function'),
    );

    protected $_link = array(
        'FamilyMember' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'FamilyMember',
            'mapping_name' => 'family_member',
            'foreign_key' => 'customer_id'
        ),
        'Family' => array(
            'mapping_type' => self::MANY_TO_MANY,
            'class_name' => 'Family',
            'mapping_name' => 'families',
            'foreign_key' => 'customer_id',
            'relation_foreign_key' => 'family_id',
            'relation_table' => 'zh_family_member'
        )
    );

    //客户编码生成
    function getCustomerId(){
        return date('YmdHis').rand(1000,9999);
    }

    protected function _before_insert(&$data, $options)
    {
        parent::_before_insert($data, $options); // TODO: Change the autogenerated stub
        if(!$data['birthday'] && $data['id_no'] != ''){
            $data['birthday'] = getBirthday($data['id_no']);
        }
    }
    protected function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
//        myDump($data);
        if(!$data['status'])
            $data['status'] = -1;
    }

    protected function _after_select(&$resultSet, $options)
    {
        parent::_after_select($resultSet, $options); // TODO: Change the autogenerated stub
        D('Dict')->dictTransform($resultSet,array('ugroup'));
    }
}
